interface ManagerInfo {
  id: string;
  name: string;
  loginTime: string;
  role?: string;
}

interface LoginCredentials {
  username: string;
  password: string;
}

interface LoginResult {
  success: boolean;
  message: string;
  data?: ManagerInfo;
}

class AuthService {
  private readonly STORAGE_KEY = 'currentManager';

  public login(managerInfo: ManagerInfo): void {
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(managerInfo));
    console.log('🔐 用户登录:', managerInfo);
    
    // 登录时初始化managerWebSocketService连接
    this.initializeWebSocketConnection(managerInfo);
  }

  public logout(): void {
    // 登出时断开WebSocket连接
    this.disconnectWebSocket();
    localStorage.removeItem(this.STORAGE_KEY);
    console.log('🚪 用户登出');
  }

  public getManager(): ManagerInfo | null {
    try {
      const stored = localStorage.getItem(this.STORAGE_KEY);
      const manager = stored ? JSON.parse(stored) : null;
      return manager;
    } catch (error) {
      console.error('Failed to parse manager info from localStorage:', error);
      return null;
    }
  }

  public isAuthenticated(): boolean {
    const isAuth = !!this.getManager();
    console.log('🔍 认证状态检查:', isAuth);
    return isAuth;
  }

  // 初始化WebSocket连接
  private initializeWebSocketConnection(managerInfo: ManagerInfo): void {
    try {
      // 动态导入managerWebSocketService，避免循环依赖
      import('./managerWebSocketService').then(({ managerWebSocketService }) => {
        managerWebSocketService.setManager(managerInfo.id, managerInfo.name);
        console.log('🔌 WebSocket连接已初始化:', managerInfo.id);
      });
    } catch (error) {
      console.error('Failed to initialize WebSocket connection:', error);
    }
  }

  // 断开WebSocket连接
  private disconnectWebSocket(): void {
    try {
      // 动态导入managerWebSocketService，避免循环依赖
      import('./managerWebSocketService').then(({ managerWebSocketService }) => {
        managerWebSocketService.disconnect();
        console.log('🔌 WebSocket连接已断开');
      });
    } catch (error) {
      console.error('Failed to disconnect WebSocket:', error);
    }
  }

  // 初始化方法 - 在应用启动时调用，检查是否已登录并初始化WebSocket
  public initialize(): void {
    const manager = this.getManager();
    if (manager) {
      console.log('🔄 应用启动，检测到已登录用户，初始化WebSocket连接');
      this.initializeWebSocketConnection(manager);
    }
  }

  // 用户名密码验证方法
  public async authenticate(credentials: LoginCredentials): Promise<LoginResult> {
    try {
      console.log('🔐 尝试验证用户:', credentials.username);
      
      const response = await fetch('/langchain-backend/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(credentials),
      });

      const result = await response.json();

      if (response.ok && result.success) {
        console.log('✅ 认证成功:', result.data.name);
        return {
          success: true,
          message: result.message,
          data: result.data
        };
      } else {
        console.log('❌ 认证失败:', result.message);
        return {
          success: false,
          message: result.message || '认证失败'
        };
      }
    } catch (error) {
      console.error('🚨 认证请求失败:', error);
      return {
        success: false,
        message: '网络错误，请稍后重试'
      };
    }
  }
}

// 导出单例
export const authService = new AuthService(); 